﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;

namespace Pub
{
    public static class CCmd
    {


        /// <summary>
        /// 运行CMD命令
        /// </summary>
        /// <param name="cmd">命令</param>
        /// <returns></returns>
        public static string Cmd(string[] sCmd)
        {
            string strRst = "";
            try
            {
                Process p = new Process();
                p.StartInfo.FileName = "cmd";    //"cmd";
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.CreateNoWindow = true;
                p.Start();
                p.StandardInput.AutoFlush = true;

                for (int i = 0; i < sCmd.Length; i++)
                {
                    p.StandardInput.WriteLine(sCmd[i].ToString());
                }

                //退出多层cmd命令行
                for (int i = 0; i < 10; i++)
                {
                    p.StandardInput.WriteLine("Exit");
                }

                StreamReader reader = p.StandardOutput;//截取输出流
                string s1 = p.StandardOutput.ReadLine();

                while (!reader.EndOfStream)
                {
                    if (s1 != null && s1 != "") strRst += "\n";
                    strRst += s1;
                    s1 = p.StandardOutput.ReadLine();

                }

                //strRst = reader.ReadToEnd();
                reader.Close();
                p.WaitForExit();
                p.Close();
            }
            catch (System.Exception ex)
            {
                CDebug.SendError(ex.ToString());
            }

            return strRst;
        }

        public static string Cmd(string sCmd)
        {
            string[] sCmd_1 = new string[] { sCmd };
            return Cmd(sCmd_1);
        }

        /// <summary>
        /// 关闭进程
        /// </summary>
        /// <param name="ProcName">进程名称</param>
        /// <returns></returns>
        public static bool CloseProcess(string ProcName)
        {
            bool result = false;
            System.Collections.ArrayList procList = new System.Collections.ArrayList();
            string tempName = "";
            int begpos;
            int endpos;
            foreach (System.Diagnostics.Process thisProc in System.Diagnostics.Process.GetProcesses())
            {
                tempName = thisProc.ToString();
                begpos = tempName.IndexOf("(") + 1;
                endpos = tempName.IndexOf(")");
                tempName = tempName.Substring(begpos, endpos - begpos);
                procList.Add(tempName);
                if (tempName == ProcName)
                {
                    if (!thisProc.CloseMainWindow())
                        thisProc.Kill(); // 当发送关闭窗口命令无效时强行结束进程
                    result = true;
                }
            }
            return result;
        }


        public static string startcmd(string command)
        {
            string output = "";
            try
            {

                Process cmd = new Process();
                cmd.StartInfo.FileName = command;

                cmd.StartInfo.UseShellExecute = false;

                cmd.StartInfo.RedirectStandardInput = true;
                cmd.StartInfo.RedirectStandardOutput = true;

                cmd.StartInfo.CreateNoWindow = true;
                cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

                cmd.Start();

                output = cmd.StandardOutput.ReadToEnd();
                Console.WriteLine(output);
                cmd.WaitForExit();
                cmd.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            return output;
        }

        public static string startcmd(string command, string argument)
        {
            string output = "";
            try
            {
                Process cmd = new Process();

                cmd.StartInfo.FileName = command;
                cmd.StartInfo.Arguments = argument;

                cmd.StartInfo.UseShellExecute = false;

                cmd.StartInfo.RedirectStandardInput = true;
                cmd.StartInfo.RedirectStandardOutput = true;

                cmd.StartInfo.CreateNoWindow = true;
                cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

                cmd.Start();

                output = cmd.StandardOutput.ReadToEnd();
                Console.WriteLine(output);
                cmd.WaitForExit();
                cmd.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            return output;
        }


        public static string RunScript(string scriptText)
        {
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();
            Pipeline pipeLine = runspace.CreatePipeline();
            pipeLine.Commands.AddScript(scriptText);
            //pipeLine.Commands.AddScript("ps");
            Collection<PSObject> results = pipeLine.Invoke();
            runspace.Close();
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString().Replace("@{ProcessName=", "").Replace("}", ""));
            }
            return stringBuilder.ToString();
        }
    }
}
